package com.example.a_java.controller.monitor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.a_java.common.Result;
import com.example.a_java.entity.SysLoginLog;
import com.example.a_java.service.SysLoginLogService;
import com.example.a_java.util.ExcelUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 登录日志Controller
 */
@Tag(name = "登录日志", description = "登录日志相关接口")
@RestController
@RequestMapping("/monitor/loginLog")
@SecurityRequirement(name = "bearer-key")
public class SysLoginLogController {

    @Autowired
    private SysLoginLogService loginLogService;

    /**
     * 获取登录日志列表
     */
    @Operation(summary = "获取登录日志列表")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('monitor:loginlog:list')")
    public Result<Page<SysLoginLog>> list(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "用户名") @RequestParam(required = false) String username,
            @Parameter(description = "登录状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "登录IP") @RequestParam(required = false) String loginIp,
            @Parameter(description = "开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        Page<SysLoginLog> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SysLoginLog> wrapper = new LambdaQueryWrapper<>();
        
        wrapper.like(StringUtils.hasText(username), SysLoginLog::getUsername, username)
                .eq(status != null, SysLoginLog::getStatus, status)
                .like(StringUtils.hasText(loginIp), SysLoginLog::getLoginIp, loginIp)
                .ge(startTime != null, SysLoginLog::getLoginTime, startTime)
                .le(endTime != null, SysLoginLog::getLoginTime, endTime)
                .orderByDesc(SysLoginLog::getLoginTime);
        
        loginLogService.page(page, wrapper);
        return Result.success(page);
    }
    
    /**
     * 导出登录日志
     */
    @Operation(summary = "导出登录日志")
    @GetMapping("/export")
    @PreAuthorize("hasAuthority('monitor:loginlog:export')")
    public void export(
            HttpServletResponse response,
            @Parameter(description = "用户名") @RequestParam(required = false) String username,
            @Parameter(description = "登录状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "登录IP") @RequestParam(required = false) String loginIp,
            @Parameter(description = "开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        LambdaQueryWrapper<SysLoginLog> wrapper = new LambdaQueryWrapper<>();
        
        wrapper.like(StringUtils.hasText(username), SysLoginLog::getUsername, username)
                .eq(status != null, SysLoginLog::getStatus, status)
                .like(StringUtils.hasText(loginIp), SysLoginLog::getLoginIp, loginIp)
                .ge(startTime != null, SysLoginLog::getLoginTime, startTime)
                .le(endTime != null, SysLoginLog::getLoginTime, endTime)
                .orderByDesc(SysLoginLog::getLoginTime);
        
        List<SysLoginLog> list = loginLogService.list(wrapper);
        
        String[] headers = {"日志编号", "用户名", "登录IP", "登录地点", "浏览器", "操作系统", "登录状态", "提示消息", "登录时间"};
        String[] fields = {"logId", "username", "loginIp", "loginLocation", "browser", "os", "status", "msg", "loginTime"};
        
        ExcelUtil.exportExcel(response, "登录日志.xlsx", "登录日志", list, headers, fields);
    }

    /**
     * 删除登录日志
     */
    @Operation(summary = "删除登录日志")
    @DeleteMapping("/{logIds}")
    @PreAuthorize("hasAuthority('monitor:loginlog:delete')")
    public Result<Boolean> delete(@PathVariable Long[] logIds) {
        return Result.success(loginLogService.removeByIds(java.util.Arrays.asList(logIds)));
    }

    /**
     * 清空登录日志
     */
    @Operation(summary = "清空登录日志")
    @DeleteMapping("/clean")
    @PreAuthorize("hasAuthority('monitor:loginlog:delete')")
    public Result<Boolean> clean() {
        loginLogService.cleanLoginLog();
        return Result.success(true);
    }
} 
